<template>
  <div class="camera-capture-container">
    <h2>实时摄像头投影</h2>
    <div class="video-container">
      <video ref="video" autoplay playsinline muted></video>
      <div v-if="!hasVideoStream" class="video-overlay">
        <i class="el-icon-video-camera-solid"></i>
        <p>{{ streamError ? '点击重新连接摄像头' : '摄像头未连接' }}</p>
      </div>
    </div>
    <div v-if="streamError" class="error-message">
      <p>错误: {{ streamError }}</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CameraCapture',
  data() {
    return {
      video: null,
      hasVideoStream: false,
      streamError: null
    };
  },
  mounted() {
    console.log('CameraCapture mounted called');
    this.video = this.$refs.video;
    this.startCamera();
  },

  beforeDestroy() {
    // 组件销毁前释放摄像头资源
    this.cleanupResources();
  },

  beforeRouteLeave(to, from, next) {
    // 路由离开前也清理资源
    this.cleanupResources();
    next();
  },

  methods: {
    cleanupResources() {
      if (this.video && this.video.srcObject) {
        try {
          const tracks = this.video.srcObject.getTracks();
          tracks.forEach(track => {
            if (track.readyState === 'live') {
              track.stop();
            }
          });
          this.video.srcObject = null;
        } catch (e) {
          console.error('清理视频资源时出错:', e);
        }
      }
      this.hasVideoStream = false;
    },
    startCamera() {
      // 重置状态
      this.hasVideoStream = false;
      this.streamError = null;

      // 清理之前可能存在的流
      if (this.video && this.video.srcObject) {
        try {
          const tracks = this.video.srcObject.getTracks();
          tracks.forEach(track => {
            track.stop();
          });
          this.video.srcObject = null;
          // 等待流完全停止
          setTimeout(() => this.initializeCamera(), 200);
        } catch (e) {
          console.error('清理之前的流时出错:', e);
          this.initializeCamera();
        }
      } else {
        // 没有之前的流，直接初始化
        this.initializeCamera();
      }
    },

    initializeCamera() {
      const constraints = {
        video: {
          width: { ideal: 1280 }, // 尝试更高分辨率
          height: { ideal: 720 },
          frameRate: { ideal: 30 }
        },
        audio: false
      };

      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        this.streamError = '您的浏览器不支持访问摄像头，请使用现代浏览器。';
        return;
      }

      navigator.mediaDevices.getUserMedia(constraints)
        .then(stream => {
          console.log('获取到摄像头流');
          if (!this.video) {
            this.video = this.$refs.video;
          }
          this.video.srcObject = stream;

          stream.getVideoTracks()[0].onended = () => {
            console.log('视频流已结束');
            this.hasVideoStream = false;
            this.streamError = '摄像头已断开';
          };

          this.video.onloadedmetadata = () => {
            console.log('视频元数据已加载，准备播放');
            const playPromise = this.video.play();

            if (playPromise !== undefined) {
              playPromise
                .then(() => {
                  console.log('视频开始播放');
                  this.hasVideoStream = true;
                })
                .catch(e => {
                  console.error('视频播放失败:', e);
                  this.streamError = '视频播放失败: ' + e.message;
                });
            }
          };
        })
        .catch(error => {
          console.error('无法访问摄像头:', error);
          this.streamError = '无法访问摄像头: ' + error.message;
        });
    }
  }
};
</script>

<style scoped>
.camera-capture-container {
  text-align: center;
  padding: 20px;
}

.video-container {
  position: relative;
  width: 100%; /* 使用百分比宽度以适应容器 */
  max-width: 1280px; /* 最大宽度 */
  margin: 20px auto;
  border: 2px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  background-color: #f2f2f2;
  aspect-ratio: 16 / 9; /* 保持16:9的宽高比 */
}

video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
}

.video-overlay i {
  font-size: 64px;
  margin-bottom: 20px;
}

.error-message {
  color: red;
  margin-top: 20px;
}
</style>
